#include "MainWindow.hpp"
#include "Director.hpp"
#include "LogDisplay.hpp"
#include <QxtBasicFileLoggerEngine>
#include <QApplication>
#include <QCloseEvent>
#include "gl.hpp"
MainWindow::MainWindow(QWidget *parent)  : QGLWidget(parent), init(false)
{
    terminate = false;
     // at the end of construction, we invoke the update() slot
    director = Director::instance();
    setGeometry(GETV("window/x").toInt(),GETV("window/y").toInt(),GETV("window/width").toInt(),GETV("window/height").toInt());
}

MainWindow::~MainWindow()
{

}

void MainWindow::runMe() {
    qxtLog->trace() << "running";
    forever {
        if(terminate) break;
        blocker.start();
        updateGL();
        while( blocker.absolute() < 0.013f) {
            qApp->processEvents();
        }
    }
    qApp->exit(0);
}

void MainWindow::initializeGL() {
    qxtLog->info("Initializing OpenGL");
    glClearColor(0.0, 0.0, 0.0, 0.0);
    glEnable(GL_DEPTH_TEST);
    init_gl();

}

void MainWindow::resizeGL(int w, int h) {
    float aspect = GETV("gl/width").toDouble()/GETV("gl/height").toDouble();
    float d = (float)w/(float)h;
    float dh = GETV("gl/height").toDouble();
    float dw = GETV("gl/width").toDouble();

    // d is the new aspect, aspect is the old aspect.
    // if d == a then nothing's changed.
    // if d < a then the window has gotten taller.
    if(d>aspect) {
        // if the new aspect is bigger, the window has stretched more horizontally.  keep the height and scale the width
        dh = float(h);
        dw = float(h)*aspect;
    } else if (d < aspect) {
        dw = float(w);
        dh = float(w)*aspect;
    } else {
        dh = float(h);
        dw = float(h)/aspect;
    }
    glViewport(0,0,dw,dh);
}

void MainWindow::paintGL() {
    // all Actor events and calculations should be run in the exact states there were in BEFORE update() happened.
    if(director) director->update(0);
    //after we're done updating... we call update again!
}

void MainWindow::keyPressEvent(QKeyEvent *event) {
    int key = event->key();
    if (key == Qt::Key_Escape) {
        terminate = true;
    }
}

void MainWindow::closeEvent(QCloseEvent *evt) {
    terminate = true;
    evt->accept();
}
